package com.spoplar.service.impl;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConfig;
import com.spoplar.dao.MerchantWxpayTradeMapper;
import com.spoplar.pojo.Merchant;
import com.spoplar.pojo.MerchantShop;
import com.spoplar.pojo.MerchantWxpayConf;
import com.spoplar.pojo.MerchantWxpayTrade;
import com.spoplar.service.IWxpayService;
import com.github.wxpay.sdk.WxPayConfigImpl;
import com.spoplar.service.ImerchantService;
import org.apache.commons.codec.binary.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by spoplar on 18-2-6.
 */
@Service("IWxpayService")
public class WxpayServiceImpl implements IWxpayService {

    private final static Logger log = LoggerFactory.getLogger(WxpayServiceImpl.class);

    private WXPay wxPay;

    @Autowired
    private ImerchantService imerchantService;

    @Autowired
    private MerchantWxpayTradeMapper merchantWxpayTradeMapper;
    /**
     * 条码支付
     * @param wxconf
     * @param data
     * @throws Exception
     */
    public  void  micropay(MerchantWxpayConf wxconf, HashMap<String,String> data, MerchantShop merchantShop) throws Exception {
        init(wxconf);



        //数据放入数据库


        MerchantWxpayTrade trade = new MerchantWxpayTrade();
        trade.setOutTradeNo(data.get("out_trade_no"));
        trade.setMerPayToken(merchantShop.getMerPayToken());
        trade.setShopPayToken(merchantShop.getShopPayToken());
        trade.setBody(data.get("body"));
        trade.setTotalFee(Integer.valueOf(data.get("total_fee")));
        trade.setAuthCode(data.get("auth_code"));
        trade.setScene("micropay");

        merchantWxpayTradeMapper.insertSelective(trade);


        Map<String, String> r = wxPay.microPay(data);
        System.out.println(r);
        trade.setNonceStr(r.get("nonce_str"));
        trade.setAppid(r.get("appid"));
        trade.setMchId(r.get("mch_id"));
        trade.setSign(r.get("sign"));

        merchantWxpayTradeMapper.updateByPrimaryKeySelective(trade);

    }

    /**
     * 扫码支付
     * @param wxconf
     * @param data
     * @throws Exception
     */
    public void qrcodepay(MerchantWxpayConf wxconf,HashMap<String,String> data , MerchantShop merchantShop) throws Exception{
         init(wxconf);

        //数据放入数据库


        MerchantWxpayTrade trade = new MerchantWxpayTrade();
        trade.setOutTradeNo(data.get("out_trade_no"));
        trade.setMerPayToken(merchantShop.getMerPayToken());
        trade.setShopPayToken(merchantShop.getShopPayToken());
        trade.setBody(data.get("body"));
        trade.setTotalFee(Integer.valueOf(data.get("total_fee")));
        trade.setScene("qrcodepay");
        trade.setDeviceInfo(data.get("device_info"));
        trade.setFeeType(data.get("fee_type"));
        trade.setSpbillCreateIp(data.get("spbill_create_ip"));
        trade.setNotifyUrl(data.get("notify_url"));
        trade.setTradeType(data.get("trade_type"));
        trade.setProductId(data.get("product_id"));

        merchantWxpayTradeMapper.insertSelective(trade);

         Map<String, String> r = wxPay.unifiedOrder(data);
         System.out.println(r);
        trade.setNonceStr(r.get("nonce_str"));
        trade.setAppid(r.get("appid"));
        trade.setMchId(r.get("mch_id"));
        trade.setSign(r.get("sign"));

        merchantWxpayTradeMapper.updateByPrimaryKeySelective(trade);
    }

    /**
     * 交易查询
     * @param wxconf
     * @param reqData
     * @throws Exception
     */
    public void query(MerchantWxpayConf wxconf,Map<String, String> reqData)  throws Exception{
        init(wxconf);
        Map<String, String> r = wxPay.orderQuery(reqData);
        String out_trade_no = r.get("out_trade_no");
        MerchantWxpayTrade trade = merchantWxpayTradeMapper.selectByOutTradeNo(out_trade_no);
        String trade_state =r.get("trade_state");
        trade.setTradeState(trade_state);
        if(trade_state.equals("SUCCESS") || org.apache.commons.lang3.StringUtils.isNotBlank(r.get("transaction_id"))){
            trade.setTransactionId(r.get("transaction_id"));
            trade.setBankType(r.get("bank_type"));
            trade.setOpenid(r.get("openid"));
            trade.setSign(r.get("sign"));
            trade.setFeeType(r.get("fee_type"));
            trade.setTimeEnd(r.get("time_end"));
        }
        merchantWxpayTradeMapper.updateByPrimaryKeySelective(trade);
    }

    /**
     *
     * @param data
     */
    public void validate(MerchantWxpayConf wxconf,Map<String,String> data)throws Exception{
        init(wxconf);
        boolean isTrue = wxPay.isPayResultNotifySignatureValid(data);
        System.out.println(isTrue);
        if(isTrue){
            Map<String,String> reqData = new HashMap<String,String>();
            reqData.put("out_trade_no",data.get("out_trade_no"));
            this.query(wxconf,reqData);
        }
    }


    /**
     * 初始化wxpay
     * @param wxconf
     * @throws Exception
     */
    private void init(MerchantWxpayConf wxconf) throws Exception {
        WXPayConfig config = new WxPayConfigImpl(wxconf.getAppid(),wxconf.getMchid(),wxconf.getAppkey());
        wxPay = new WXPay(config);
    }






}
